package GDoc::Agency;

use Moose;
use Carp 'croak';

use GDoc::Const 'SITE_CONF';
use GDoc::Listing;


our @CONF;
BEGIN { 
    my $tmp = do { 
        local $/; 
        open my $fh, '<', SITE_CONF or die "Can't open " . SITE_CONF . " $!";
        YAML::XS::Load( <$fh> );
    };

    @CONF = @{ $tmp };
}


has 'type'       => ( is        => 'ro',
                      isa       => 'Str',
                      required  => 1
                    );

has 'name'       => ( is        => 'ro',
                      isa       => 'Str',
                      required  => 1 
                    );

has 'output'     => ( is        => 'ro',
                      isa       => 'Str',
                      required  => 1
                    );

has 'index'      => ( is        => 'ro',
                      isa       => 'Str',
                      required  => 1 
                    );

has 'desc'       => ( is        => 'ro',
                      isa       => 'Str',
                      required  => 1
                    );

has 'listings'   => ( is        => 'rw',
                      isa       => 'ArrayRef',
                      required  => 0,
                    );

has 'agencies'   => ( is        => 'rw',
                      isa       => 'ArrayRef',
                      required  => 0,
                    );

has 'crumbs'     => ( is        => 'rw',
                      isa       => 'ArrayRef',
                      required  => 0
                    );

sub BUILD { 
    my $self = shift;

    my $idx = $self->index;
    my @listings = map { GDoc::Listing->new( $_ ) }
                   grep { ( $_->{type}   =~ /^listing/ ) and 
                          ( $_->{index}  =~ m{^$idx/\w+$} )
                        } @CONF;

    $self->listings( \@listings );

    my @agencies = map { GDoc::Agency->new( $_ ) }
                   grep { ( $_->{type}   eq 'agency' ) and
                          ( $_->{index}  =~ m{^$idx/\w+$} )
                        } @CONF;

    $self->agencies( \@agencies );

    # set up breadcrumbs
    my @parts = grep { length } split '/', $self->index;
    my @crumbs;

    my $path;
    foreach my $part( @parts ) {
        $path .= '/' . $part;
        my ( $thing ) = grep { $_->{index} eq $path } @CONF;
        push @crumbs, { path => $path, name => ( $thing->{name} or 'US' ) };
    }

    $self->crumbs( \@crumbs );
}

1;



